package com.irdstudio.efp.nls.service.impl.psd.credit;

import com.irdstudio.basic.framework.core.base.FrameworkService;
import com.irdstudio.efp.console.common.ConsoleConstant;
import com.irdstudio.efp.console.common.psd.PsdConstantSet;
import com.irdstudio.efp.console.service.facade.PubSysInfoService;
import com.irdstudio.efp.console.service.facade.SOrgService;
import com.irdstudio.efp.ctr.service.facade.CtrLoanContService;
import com.irdstudio.efp.ctr.service.vo.CtrLoanContVO;
import com.irdstudio.efp.cus.service.facade.CusIndivService;
import com.irdstudio.efp.edoc.service.facade.CfcaSignInfoService;
import com.irdstudio.efp.edoc.service.facade.signature.PsdCertUploadService;
import com.irdstudio.efp.edoc.service.facade.signature.PsdContService;
import com.irdstudio.efp.limit.service.facade.LmtPrdContService;
import com.irdstudio.efp.limit.service.vo.LmtPrdContVO;
import com.irdstudio.efp.nls.common.constant.NlsApplyInfoEnums;
import com.irdstudio.efp.nls.service.dao.sx.NlsCreditInfoDao;
import com.irdstudio.efp.nls.service.domain.sx.NlsCreditInfo;
import com.irdstudio.efp.nls.service.facade.psd.NlsCreditApprovalInfoService;
import com.irdstudio.efp.nls.service.facade.psd.PsdSxCtrCheckService;
import com.irdstudio.efp.nls.service.vo.psd.NlsCreditApprovalInfoVO;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.util.StopWatch;

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 普税贷授信合同签署校验定时器
 *
 * @author xiaojunhui
 */
@Service("psdSxCtrCheckService")
public class PsdSxCtrCheckServiceImpl implements PsdSxCtrCheckService, FrameworkService {

    private static Logger logger = LoggerFactory.getLogger(PsdSxCtrCheckServiceImpl.class);

    @Autowired
    @Qualifier("cusIndivService")
    private CusIndivService cusIndivService;

    @Autowired
    @Qualifier("cfcaSignInfoService")
    private CfcaSignInfoService cfcaSignInfoService;

    @Autowired
    @Qualifier("ctrLoanContService")
    private CtrLoanContService ctrLoanContService;

    @Autowired
    @Qualifier("lmtPrdContService")
    private LmtPrdContService lmtPrdContService;

    @Autowired
    private NlsCreditInfoDao nlsCreditInfoDao;

    @Autowired
    @Qualifier("sOrgService")
    private SOrgService sOrgService;

    @Autowired
    private PsdContService psdContService;

    @Autowired
    private PsdCertUploadService psdCertUploadService;

    @Autowired
    private NlsCreditApprovalInfoService nlsCreditApprovalInfoService;

    @Autowired
    private PubSysInfoService pubSysInfoService;

    private final double limit = 1000.00;

    @Override
    public Boolean check() {
        StopWatch stopwatch = new StopWatch("授信合同签署校验定时器");
        stopwatch.start();
        try {
            //分页查询所有普税贷待额度带生效的数据
            NlsCreditInfo param = new NlsCreditInfo();
            param.setPrdId(PsdConstantSet.prdId);
            param.setApprvSts(NlsApplyInfoEnums.NlsApplyState.PASS.getKey());
            //先查总数
            //int[]{(queryPageNo-1)*limt,limt,queryPageNo};
            int totalSize = nlsCreditInfoDao.countByPrdIdAndApprvSts(param);
            logger.info("授信合同签署校验定时器，获取到的授信申请总条数为：[{}]", totalSize);
            if (totalSize <= 0) {
                return Boolean.TRUE;
            }
            int totalPage = (int) Math.ceil(totalSize / limit);
            for (int i = 0; i < totalPage; i++) {
                List<NlsCreditInfo> nlsCreditInfos = nlsCreditInfoDao.queryByPrdIdAndApprvSts(param, new RowBounds((int) (i * limit), (int) limit));
                for (NlsCreditInfo creditInfo : nlsCreditInfos) {
                    //获取风控审批的时间
                    NlsCreditApprovalInfoVO nlsCreditApprovalInfoVO = nlsCreditApprovalInfoService.selectByPrimaryKey(creditInfo.getLmtApplySeq());
                    if (Objects.isNull(nlsCreditApprovalInfoVO)) {
                        logger.info("授信合同签署校验定时器，根据授信申请信息获取授信审批记录为空，暂时跳过本条处理。授信流水号：[{}]",creditInfo.getLmtApplySeq());
                        continue;
                    }
                    Date approveTime = nlsCreditApprovalInfoVO.getApproveTime();
                    if (Objects.isNull(approveTime)) {
                        logger.info("授信合同签署校验定时器，根据授信申请信息获取到风控审批时间为空，暂时跳过本条处理。授信流水号：[{}]",creditInfo.getLmtApplySeq());
                        continue;
                    }
                    //判断额度表是否存在
                    LmtPrdContVO lmtPrdContVO = lmtPrdContService.qryLmtPrdContByLmtApplySeq(creditInfo.getLmtApplySeq());
                    if (Objects.isNull(lmtPrdContVO)) {
                        logger.info("授信合同签署校验定时器，根据授信申请信息获取到的额度记录为空，暂时跳过本条处理。授信流水号：[{}]",creditInfo.getLmtApplySeq());
                        continue;
                    }
                    if (!lmtPrdContVO.getLmtStatus().equals(ConsoleConstant.LIMIT_STS_01)) {
                        logger.info("授信合同签署校验定时器，根据授信申请信息获取到的额度记录为空，暂时跳过本条处理。授信流水号：[{}]",creditInfo.getLmtApplySeq());
                        continue;
                    }
                    //判断是否签订合同 如果未签订合同并且风控审批时间超过了三个月
                    CtrLoanContVO ctrLoanContVO = ctrLoanContService.queryContNoByLmtContNoAndContype(lmtPrdContVO.getLmtContNo(), ConsoleConstant.CONT_TYPE_01);
                    if (Objects.isNull(ctrLoanContVO) || !ctrLoanContVO.getContState().equals("200")) {
                        //未签订合同，判断审批时间是否超过了三个月
                        LocalDate apprvLocalDate = approveTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                        boolean b = apprvLocalDate.plusMonths(3).toEpochDay() < LocalDate.now().toEpochDay();
                        if (b) {
                            logger.info("授信合同签署校验定时器，需要更改额度和授信状态为失效，风控审批时间为：[{}],合同信息是否存在：[{}],合同状态为：[{}]。授信流水号：[{}]",
                                    apprvLocalDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")),
                                    Objects.isNull(ctrLoanContVO)?"否":"是",
                                    Objects.isNull(ctrLoanContVO)?"":ctrLoanContVO.getContState(),
                                    creditInfo.getLmtApplySeq());
                            //超过了三个月
                            //修改授信申请为失效
                            //修改额度状态为终止
                            nlsCreditInfoDao.updateApprvSts("06", creditInfo.getLmtApplySeq());
                            lmtPrdContService.updateLmtStatus("03", lmtPrdContVO.getLmtContNo());
                        }
                    }
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("授信合同签署校验定时器执行发生异常，异常信息为：[{}]", e.getMessage());
        } finally {
            stopwatch.stop();
            String s = stopwatch.prettyPrint();
            logger.info("授信合同签署校验定时器执行结束，执行效率为：[{}]", s);
        }
        return Boolean.TRUE;
    }
}
